package com.hypo;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

import com.aliyun.oss.*;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyuncs.exceptions.ClientException;

public class OssJavaSdkQuickStart {


    //public static void main(String[] args) throws Exception {
    //    String content="123456";
    //    String fileName="123.txt";
    //    upload(content.getBytes(),fileName);
    //}
    public static String upload(byte[] content,String fileName) throws Exception {
        // Endpoint以华东1（杭州）为例，填写为https://oss-cn-hangzhou.aliyuncs.com，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String bucketName = "hypo-java";
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-beijing";

        // 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();
        // 1. 创建存储空间（Bucket）
        ossClient.createBucket(bucketName);
        System.out.println("1. Bucket " + bucketName + " 创建成功。");
        // 2. 上传文件
        String fileDateName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String objectName = fileDateName+"/"+fileName;
        ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
        System.out.println("文件 " + objectName + " 上传成功。");
        String url=endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+objectName;
        return url;
    }
}